package cn.chiship.sdk.core.useragent;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class PatternBasedVersionFetcher implements VersionFetcher {

	private static final int TWO = 2;

	private final Pattern pattern;

	PatternBasedVersionFetcher(String regex) {
		this(Pattern.compile(regex, 2));
	}

	PatternBasedVersionFetcher(Pattern pattern) {
		this.pattern = pattern;
	}

	@Override
	public final Version version(String userAgentString) {
		Matcher matcher = this.pattern.matcher(userAgentString);
		if (!matcher.find()) {
			return null;
		}
		return createVersion(matcher);
	}

	protected Version createVersion(Matcher matcher) {
		String fullVersionString = matcher.group(1);
		String majorVersion = matcher.group(2);
		String minorVersion = "0";
		if (matcher.groupCount() > TWO) {
			minorVersion = matcher.group(3);
		}
		return new Version(fullVersionString, majorVersion, minorVersion);
	}

}
